package com.basics.framework.config.jwt;

import com.basics.api.vo.UserInfo;
import com.basics.common.utils.redis.RedisUtil;
import com.basics.framework.constants.SecurityConstants;
import com.basics.framework.utils.JwtYzUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 拦截器
 *
 * @author WangWei
 * @date 2021/8/16
 */
@Component
@Slf4j
public class YzTokenInterceptor implements HandlerInterceptor {

    //白名单列表
    private static List<String> whiteList = Arrays.asList(
            "/api/login",
            "/api/organization/joinOrganizationByPhone",
            "/api/organization/getOrganizationForH5"
    );

    @Autowired
    private RedisUtil redisUtil;

    private boolean isUrlInWhiteList(String url) {
        for (String pattern : whiteList) {
            // 使用 startsWith() 方法判断当前 URL 是否以白名单中的字符串开头
            if (url.startsWith(pattern)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info(" >>> 进来 -------------------------请求URL：{}------------------开始执行拦截器", request.getRequestURI());
        String uri = request.getRequestURI();

        if (!this.isUrlInWhiteList(uri)) {
            String prefix_token = request.getHeader(SecurityConstants.TOKEN_HEADER);
            log.error(">>>>>prefix_token----------------------{}",prefix_token);
            if (StringUtils.isEmpty(prefix_token)) {
                throw new AuthenticationException("token 失效");
            }
            if (prefix_token != null && prefix_token.startsWith(SecurityConstants.TOKEN_PREFIX)) {
                String token = prefix_token.replace(SecurityConstants.TOKEN_PREFIX, "");
                Boolean tokenExpired = JwtYzUtils.isTokenExpired(token);
                if (tokenExpired) {
                    throw new AuthenticationException("token 过期");
                }
                String userId = JwtYzUtils.getUserIdFromToken(token);
                if (StringUtils.isEmpty(userId)) {
                    throw new AuthenticationException("token 失效");
                }
                Object obj = redisUtil.get(SecurityConstants.TOKEN_PREFIX+userId);
                log.error(">>>>>obj----------------------{}",obj);
                if(obj==null){
                    throw new AuthenticationException("token 失效");
                }
                if(!token.equals(obj.toString())){
                    throw new AuthenticationException("token 失效");
                }
                /**
                 * 用户登录成功后 初始化基本信息到BLContext
                 */
                UserInfo info = JwtYzUtils.getUserFromToken(token);
                BLContext.setValue(SecurityConstants.USER_ATTRIBUTES, info);

            } else {
                throw new AuthenticationException("token 错误");
            }
        }
        return true;
    }


}
